<?php
namespace App\Http\Controllers\Api;

use App\Models\Books;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redis;

class IndexController extends Controller{

    protected $pageSize;

    function __construct()
    {
        $this->pageSize = Input::get('pageSize',10);
    }


    /*
    * 首页接口
    * return array $data 返回数据
    */
    function index(){

        $data['bookList'] = Books::getBookList();

        return jsonSuccessData($data);
    }

    /*
     * 首页更新列表
     * */
    function updateList(){

        $order = [
            'updated_at'=>'desc',
        ];
        $data['bookList'] = Books::getBookList([],[],$order);

        return jsonSuccessData($data);
    }

    /*
     *  首页完本列表
     * */
    function overList(){

        $where = [
            'is_over' => '2'
        ];

        $data['bookList'] = Books::getBookList($where);

        return jsonSuccessData($data);
    }

    /*
     *  首页分类列表接口
     * */
    function typeList(){

        $key = config('cacheKey.typeList');
        $typeList = Redis::get($key);
        if (empty($typeList)){
            $typeList = get_bookType(0);
            foreach ($typeList as $k=>$v){
                $typeList[$k]['bookList'] = Books::getBookList(['type'=>$v['id']],[],[],false);
            }
            Redis::setex($key,86400*7,json_encode($typeList));
        }else{
            $typeList = !empty($typeList)?json_decode($typeList,true):[];
        }

        return jsonSuccessData($typeList);
    }

    /*
    *  首页分类列表接口
    * */
    function bannerList(){

        $type = Input::get('type',1);
        $key = config('cacheKey.bannerList').$type;
        $data = Redis::get($key);
        if (empty($data)){
            $where = [
                'type' => $type
            ];
            $data = Books::getBookList($where,[],[],false);
            //防止缓存穿透
            if (!empty($data)){
                Redis::setex($key,86400,$data);
            }else{
                Redis::setex($key,30,[]);
            }
        }
        $data = !empty($data)?json_decode($data,true):[];

        return jsonSuccessData(['bookList'=>$data]);
    }

    /*
     *  点击排行榜数据
     * */
    function clickList(){

        $order = [
            'click_num' => 'desc'
        ];

        $data['bookList'] = Books::getBookList([],[],$order);

        return jsonSuccessData($data);
    }
}